import bpy
import random
import math

# 清除当前场景中的网格对象（可选）
bpy.ops.object.select_all(action='DESELECT')
bpy.ops.object.select_by_type(type='MESH')
bpy.ops.object.delete()

# 定义生成区域的大小
area_size = 100

# 生成100个边长为10的立方体
for i in range(100):
    # 随机位置
    x = random.uniform(-area_size, area_size)
    y = random.uniform(-area_size, area_size)
    z = random.uniform(0, area_size)
    
    # 创建立方体
    bpy.ops.mesh.primitive_cube_add(size=10, enter_editmode=False, align='WORLD', location=(x, y, z))
    
    # 获取当前创建的物体并命名
    cube = bpy.context.active_object
    cube.name = f"Cube_{i+1}"
    
    # 可选：给每个立方体一个随机旋转
    rx = random.uniform(0, math.pi*2)
    ry = random.uniform(0, math.pi*2)
    rz = random.uniform(0, math.pi*2)
    cube.rotation_euler = (rx, ry, rz)
    
    # 可选：随机材质颜色
    mat = bpy.data.materials.new(name=f"Material_{i+1}")
    mat.diffuse_color = (random.random(), random.random(), random.random(), 1.0)
    
    if cube.data.materials:
        cube.data.materials[0] = mat
    else:
        cube.data.materials.append(mat)

print("已创建100个边长为10的立方体")







import bpy

# 清除场景
bpy.ops.object.select_all(action='DESELECT')
bpy.ops.object.select_by_type(type='MESH')
bpy.ops.object.delete()

# 设置布局参数
grid_size = 5  # 5x5x4 的网格
cube_size = 10  # 边长10
spacing = cube_size * 1.2  # 间距为立方体大小的1.2倍

count = 0
for z in range(4):  # 4层
    for y in range(grid_size):
        for x in range(grid_size):
            if count >= 100:  # 达到100个后停止
                break
                
            # 计算位置
            pos_x = x * spacing
            pos_y = y * spacing
            pos_z = z * spacing
            
            # 创建立方体
            bpy.ops.mesh.primitive_cube_add(size=cube_size, 
                                           location=(pos_x, pos_y, pos_z))
            cube = bpy.context.active_object
            cube.name = f"Cube_{count+1}"
            
            count += 1
            
            if count >= 100:
                break
        if count >= 100:
            break

print(f"已创建{count}个边长为10的立方体")








import bpy
import random

# 清空场景
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete()

# 生成100个立方体
for i in range(100):
    # 随机位置
    x = random.uniform(-10, 10)
    y = random.uniform(-10, 10)
    z = random.uniform(-10, 10)
    
    # 随机大小
    size = random.uniform(0.5, 2.0)
    
    # 创建立方体
    bpy.ops.mesh.primitive_cube_add(
        size=size,
        location=(x, y, z)
    )
    
    # 随机颜色材质
    mat = bpy.data.materials.new(name=f"Material_{i}")
    mat.diffuse_color = (
        random.random(),
        random.random(),
        random.random(),
        1.0
    )
    bpy.context.object.data.materials.append(mat)
